﻿using System;
using Google.GData.Client;
using Google.GData.YouTube;
using Google.YouTube;

namespace LoveMusic.Helpers
{
    public class YouTubeApi
    {

        #region Properties

        private string Description
        {
            get;
            set;
        }

        private string EncodingCode
        {
            get;
            set;
        }

        private string VideoID
        {
            get;
            set;
        }

        private string SEARCH_TERM
        {
            get;
            set;
        }

        private string ARTIST
        {
            get;
            set;
        }

        private string SONG_NAME
        {
            get;
            set;
        }

        private int BROJAC
        {
            get;
            set;
        }

        private string TAGS
        {
            get;
            set;
        }

        private Video CANDIDAT
        {
            get;
            set;
        }

        #endregion Properties

        public void GetYouTubeVideo(string songTitle, string artistName, ref string encodingCode, ref string videoID, ref string tags, ref string description)
        {
            //YouTubeApi apiYouTube = new YouTubeApi();

            ARTIST = artistName.Replace("'","");
            SONG_NAME = songTitle.Replace("'","");
            ARTIST =WebHelper.RemoveSpecialCharactersExceptAmpersand(ARTIST);
            SONG_NAME = WebHelper.RemoveSpecialCharactersExceptAmpersand(SONG_NAME);

            BROJAC = -1;

            try
            {
                DoWork();
                if (EncodingCode != null)
                {
                    encodingCode = EncodingCode;
                    tags = TAGS;
                    videoID = VideoID;
                    description = Description;
                }
                else
                {
                    encodingCode = string.Empty;
                    tags = string.Empty;
                    videoID = string.Empty;
                    description = string.Empty;
                }
            }
            catch (Exception ex)
            {
                TraceLog.TimeWrite(ex, "GetYouTubeVideo()");
            }
        }

      

        private void DoWork()
        {
            SEARCH_TERM = GetSearchTerm();
            if (SEARCH_TERM != String.Empty)
            {
                String CLIENT_ID = "ytapi-AleksandarAleksa-ILoveThisMusic-dg3obda3-0";
                String DEVELOPER_KEY = "AI39si5HXOeVD-j3zHRlVjPXvgVzZWz3eV91Caxo7et6iC4JO8g7IztWH12wzV5uwwnsAt2pUWBTRbw75ph4WnuGIw4a83hStA";
                String feedUrl = "http://gdata.youtube.com/feeds/api/videos?q=" + SEARCH_TERM
                    + "&client=" + CLIENT_ID + "&key=" + DEVELOPER_KEY + "&category=Music";
                YouTubeRequestSettings settings = new YouTubeRequestSettings("ILoveThisMusic", CLIENT_ID, DEVELOPER_KEY);
                settings.Maximum = 15;
                YouTubeRequest request = new YouTubeRequest(settings);

                Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
                if (videoFeed.TotalResults == 0 && SEARCH_TERM != String.Empty)
                    DoWork();
                else
                    if (SEARCH_TERM != String.Empty)
                        FindVideo(videoFeed);
                    else
                        EncodingCode = String.Empty;
            }
        }

        private string GetSearchTerm()
        {
            BROJAC = BROJAC + 1;
            switch (BROJAC)
            {
                case 0:
                    return "%22" + ARTIST + "+" + SONG_NAME + "%22";
                case 1:
                    return "%22" + ARTIST + " " + SONG_NAME + "%22";
                case 2:
                    return ARTIST + " " + SONG_NAME;
                case 3:
                    return SONG_NAME;
                case 4:
                    return ARTIST;
                default:
                    SONG_NAME = SONG_NAME.Substring(0, SONG_NAME.Length - 1);
                    return SONG_NAME;
            }
        }

        /// <summary>
        /// List all videos, it should check the duration of all videos to be larger 
        /// than 120 seconds and other parametars to find the best video possible
        /// </summary>
        /// <param name="feed"></param>
        private void FindVideo(Feed<Video> feed)
        {
            int counter = 0;
            bool exactMatch = false;

            AtomCategory categoryMusic = new AtomCategory("Music", YouTubeNameTable.CategorySchema);
            feed.AtomFeed.Categories.Add(categoryMusic);

            foreach (Video entry in feed.Entries)
            {
                if (counter > 50)
                    break;
                int videoDuration = Int32.Parse(entry.Media.Duration.Seconds);

                if (videoDuration >= 60)
                {
                    if (entry.Media.Title.Value.ToLower().Contains(SONG_NAME.ToLower()) && entry.Media.Title.Value.ToLower().Contains(ARTIST.ToLower()))
                    {// Found exact match
                        if (counter == 0)
                            CANDIDAT = entry; // first time set candidat to first video
                        else
                        {//search for a better candidat
                            // if the video is more viewed its better
                            try
                            {
                                //if (Int32.Parse(entry.Media.Duration.Seconds) > Int32.Parse(CANDIDAT.Media.Duration.Seconds))
                                //    CANDIDAT = entry;
                                if (entry.ViewCount > CANDIDAT.ViewCount)
                                    CANDIDAT = entry;
                            }
                            catch (Exception ex)
                            {
                                TraceLog.TimeWrite(ex, "FindVideo - YoutubeApi");
                            }
                        }
                        counter++;
                    }
                }

            }
            if (CANDIDAT != null)
                setVideo(CANDIDAT);
        }
        /// <summary>
        /// Sets the video to the EncodingCode Holder
        /// </summary>
        /// <param name="entry"></param>
        private void setVideo(Video entry)
        {
            TAGS = entry.Keywords;
            String videoID = entry.Media.VideoId.Value;
            VideoID = videoID;
            EncodingCode = RenderVideoEmbedded(videoID);
            Description = entry.Description;
        }

        /// <summary>
        /// Gets html code to display video
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string RenderVideoEmbedded(string id)
        {
            EncodingCode = string.Format("<div id=\"video{0}\"><object width=\"425\" height=\"355\"><param name=\"movie\" value=\"http://www.youtube.com/v/{0}&rel=1\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/{0}&rel=1\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"355\"></embed></object></div>", id);
            return EncodingCode;
        }


    }
}